#include "ProtectedQ.h"
using namespace std;
#include <iostream>

ProtectedQ::ProtectedQ() {
	if (pthread_mutex_init(&queue_lock, NULL) != 0) {
		perror("Queue lock initialization");
		exit(1);
	}

}

ProtectedQ::~ProtectedQ() {
	pthread_mutex_destroy(&queue_lock);
}

void ProtectedQ::push(Message* msg) {
//	cout<<"ProtectedQ::push"<<endl;
//	cout<<msg->toString()<<endl;
	pthread_mutex_lock(&queue_lock);
	inbox.push(msg);
	pthread_mutex_unlock(&queue_lock);
}

Message * ProtectedQ::pop() {
	pthread_mutex_lock(&queue_lock);
	Message * msg = inbox.front();
	inbox.pop();
	pthread_mutex_unlock(&queue_lock);
	return msg;
}

int ProtectedQ::size() {
	int size;
	pthread_mutex_lock(&queue_lock);
	size = inbox.size();
	pthread_mutex_unlock(&queue_lock);
	return size;

}

void ProtectedQ::clear() {
	pthread_mutex_lock(&queue_lock);
	while(!inbox.empty()) inbox.pop();
	pthread_mutex_unlock(&queue_lock);
}
